import React, {useRef ,useImperativeHandle } from 'react';
import { Modal, Form, Input, message, Button, Popconfirm, Select } from 'antd';

const { Option } = Select;

const FormItem = Form.Item;
let options = [];
const SimCardBindingForm = React.forwardRef((props, ref) => {
    const { visible, titleType, onCancel, handleSimCreate, handleVinCreate,
       handleSubmit, confirmType, originDevice, setDevice,
      setConfirmType, typeDisabled, buttonLoading} = props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
    // const formRef = useRef();
    // useImperativeHandle(ref, () => {
    //   console.log(formRef);
    //   return formRef.current;
    // })
    return (
      <Modal
        visible={visible}
        title={titleType}
        onCancel={onCancel}
        handleSimCreate={handleSimCreate}
        handleVinCreate={handleVinCreate}
        options={options}
        confirmType={confirmType}
        originDevice={originDevice}
        footer={[
          <Button key="back" size="default" onClick={onCancel}>
            返回
          </Button>,
          <Popconfirm  key="edit" title={confirmType[1]} onConfirm={handleSimCreate}>
            <Button loading={buttonLoading} type="primary" size="default" disabled={confirmType[1] === ''}>
              修改
            </Button>
          </Popconfirm>
        ]}
      >
        <Form onFinish={handleSubmit} ref={ref}>
          <FormItem
            {...formItemLayout}
            label="SIM卡编号"
            name='fittingId'
            rules={[{
              required: true, message: '',
            }]}
          >
            
              <Input placeholder="" disabled />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="MSISDN"
            name='msisdn'
            rules={[{
              required: true, message: '',
            }]}
          >
            <Input placeholder="" disabled />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="设备类型"
            name='deviceType'
            rules={[{
              required: true, message: '请选择',
            }]}
          >
            
            <Select placeholder="请选择设备类型" disabled={typeDisabled}>
              <Option value="2">TBOX</Option>
              <Option value="4">车机</Option>
            </Select>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="设备编号"
            name='deviceId'
            rules={[{
              required: false, message: '请输入设备编号',
            }]}
          >
            <Input
              placeholder="为空则解除原有绑定"
              onChange={(e) => {
                const v = e.target.value;
                setDevice(v);
                if (!originDevice) {
                  if (v.trim()) {
                    confirmType[1] = '确定要绑定该设备吗?';
                  } else {
                    confirmType[1] = '';
                  }
                } else if ((v) && (originDevice !== v)) {
                  confirmType[1] = '确定要绑定该设备吗?';
                } else if ((v) && (originDevice === v)) {
                  confirmType[1] = '';
                } else {
                  confirmType[1] = '确定解除与该设备的绑定吗?';
                }
                setConfirmType(confirmType);
              }}
            />
          </FormItem>
        </Form>
      </Modal>
    );
  }
)
class simCardBindingModel extends React.Component {
  state = {
    typeDisabled: false,
    visible: false,
    titleType: '',
    confirmType: ['', ''],
    origin_device: '',
    modify_device: '',
    page: '',
    formValues: '',
    buttonLoading: false,
  };
  formRef = React.createRef();
  componentWillMount() {
  }
  componentDidMount() {
  }
  showModalEdit = async (e) => {
    await this.setState({
      visible: true,
    });
    this.formRef.current.setFieldsValue({
      fittingId: e.deviceId,
      msisdn: e.msisdn,
      deviceType: e.deviceType ? e.deviceType : undefined,
      deviceId: e.groupDevice,
    });
    if (e.deviceType) {
      this.setState({
        typeDisabled: true,
      });
    }
    this.setState({
      visible: true,
      titleType: '修改绑定关系',
      origin_device: e.groupDevice,
      modify_device: e.groupDevice,
      confirmType: ['', ''],
      page: e.page,
      formValues: e.formValues,
    });
  }
  handleCancel = () => {
    const { page, formValues } = this.state;
    const { dispatch } = this.props;
    this.formRef.current.resetFields();
    dispatch({
      type: 'simCard/fetch',
      payload: {
        current: page.current - 1,
        pageSize: page.pageSize,
        ...formValues,
      },
    });
    options = [];
    this.setState({
      visible: false,
      typeDisabled: false,
    });
  }

  handleSimCreate = (e) => {
    e.preventDefault();
    const { page, formValues } = this.state;
    this.formRef.current.validateFields().then((values) => {
      // console.log(err, values);
      // if (!err) {
        this.setState({
          buttonLoading: true,
        });
        const obj = values;
        obj.originDeviceId = this.state.origin_device;
        this.props.dispatch({
          type: 'simCard/bindingDevice',
          payload: obj,
          callback: (data) => {
            if (data.statusCode === '0') {
              message.success('操作成功');
              this.setState({
                visible: false,
                origin_device: this.state.modify_device,
                confirmType: [this.state.confirmType[0], ''],
                typeDisabled: false,
              });
              this.props.dispatch({
                type: 'simCard/fetch',
                payload: {
                  page: page.current - 1,
                  size: page.pageSize,
                  ...formValues,
                },
              });
            } else {
              // message.error(data.statusMessage, 3);
            }
            this.setState({
              buttonLoading: false,
            });
          },
        });
      // }
    });
  }

  render() {
    // const confirmType = ['确定要绑定该VIN号吗?', '确定要解绑该VIN号吗?', '确定要绑定该SIM卡号吗?', '确定要解绑该SIM卡号吗?'];
    return (
      <div>
        <SimCardBindingForm
          ref={this.formRef}
          typeDisabled={this.state.typeDisabled}
          visible={this.state.visible}
          titleType={this.state.titleType}
          onCancel={this.handleCancel}
          handleVinCreate={this.handleVinCreate}
          handleSimCreate={this.handleSimCreate}
          handleSubmit={this.handleSubmit}
          confirmType={this.state.confirmType}
          originDevice={this.state.origin_device}
          setDevice={device =>
            this.setState({ modify_device: device })}
          setConfirmType={newType =>
            this.setState({ confirmType: newType })}
          buttonLoading={this.state.buttonLoading}
        />
      </div>
    );
  }
}

export default simCardBindingModel;
